library(ggplot2)
library(reshape2)

# Creating the new data frame from the provided table, converting percentage values to decimals
df <- data.frame(
  Party = c("Total", "Democrat", "D. Lean", "Republican", "R. Lean", "Other"),
  `No aid` = c(15.3, 4.04, 7.8, 38.4, 37.0, 24.1) / 100,
  `$0.5 - $1.5bn` = c(30.0, 25.4, 32.3, 35.9, 38.5, 26.3) / 100,
  `$2bn - $5bn` = c(16.3, 20.4, 17.4, 9.4, 10.3, 5.8) / 100,
  `$6bn - $10bn` = c(10.3, 13.1, 10.4, 6.0, 5.7, 5.1) / 100,
  `$11bn - $15bn` = c(22.0, 29.4, 24.0, 8.6, 7.4, 23.36) / 100,
  `More than $15bn` = c(6.1, 7.7, 8.0, 1.7, 1.1, 15.3) / 100,
  check.names = FALSE
)

# Sorting parties based on 'No aid' values
df <- df[order(-df$`No aid`),]
df$Party <- factor(df$Party, levels = df$Party)

# Melting the data for use with ggplot
data_long <- melt(df, id.vars = "Party", variable.name = "Aid Amount")

# Ensuring the order of 'Aid Amount' is as desired
data_long$`Aid Amount` <- factor(data_long$`Aid Amount`, levels = c("More than $15bn", "$11bn - $15bn", "$6bn - $10bn", "$2bn - $5bn", "$0.5 - $1.5bn", "No aid"))

# Map custom colors to aid amount levels
custom_colors <- c(`No aid` = "red", `$0.5 - $1.5bn` = "orange", `$2bn - $5bn` = "yellow",
                   `$6bn - $10bn` = "white", `$11bn - $15bn` = "lightblue", `More than $15bn` = "blue")

# Create the stacked bar plot
ggplot(data_long, aes(x = Party, y = value, fill = `Aid Amount`)) +
  geom_bar(stat = "identity", position = "stack", colour = "black") +
  geom_text(aes(label = sprintf("%1.0f", value * 100)), position = position_stack(vjust = 0.5), color = "black", size = 3) +
  scale_fill_manual(values = custom_colors) +
  scale_y_continuous(labels = scales::percent_format()) +
  coord_flip() +
  labs(y = "", x = "", fill = "Aid Amount", 
       title = "Preferred US Pledge to the Global Climate Fund by Party") +
  theme_minimal() +
  theme(panel.grid.major.y = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x = element_line(colour = "gray"),
        legend.position = "bottom")

# Save the plot
ggsave("MessagingFigsR/climate_fund_aid.png", width = 10, height = 6, dpi = 300)
